import * as fs from "fs";
import * as path from "path";
import config from "./config";
import log from "./logger";
import sender from "./sender";
import * as readline from "readline";
import {TrainCO, TrainNodeCO} from "./interface";
import excelFulongCollector from "./excelfulongcollector";


function compareTimes(newTime: Date, oldTime: Date) {
    if (newTime.getTime() - oldTime.getTime() < 10 * 60 * 1000) {
        return true;
    } else {
        return false;
    }
}

interface Group {
    carType: string
    carNumber: string
    time: string
}

class LogFulongCollector {
    private currentGroup: Group[] = [];
    private lastTime: any = null;

    init() {
        this.collection().catch((e) => {
            log.info(e);
        });
        setInterval(() => {
            this.collection().catch((e) => {
                log.info(e);
            });
        }, 1000 * 60 * 2)
    }

    async collection() {
        let startPath = '//192.168.1.20/煤机装车报表系统V1.3/Log'
        let files = fs.readdirSync(startPath);
        // log.info("files:", files)
        let filelist: any[] = [];
        for (let i = 0; i < files.length; i++) {
            let filename = path.join(startPath, files[i]);
            // log.info("filename:", filename)
            if (files[i].indexOf(".log") >= 0 && files[i].startsWith("Data_RF") && !files[i].startsWith(".")) {
                let stat = fs.lstatSync(filename);
                filelist.push({path: filename, mtime: stat.mtime, ctime: stat.ctime});
            }
        }
        // 根据修改时间排序
        filelist.sort(function (a: any, b: any) {
            return b.mtime - a.mtime;
        });
        let fileSlice = filelist.slice(0, 2);
        log.info("fileSlice:", fileSlice)
        for (let i = fileSlice.length - 1; i >= 0; i--) {
            const fileStream = fs.createReadStream(fileSlice[i].path);

            const rl = readline.createInterface({
                input: fileStream,
                crlfDelay: Infinity
            });
            for await (const line of rl) {
                // rl.on('line', async (line) => {
                // log.info(`Line from file: ${line}`);
                // [2024-01-09 20:40:53]:TC70   163553113W102
                // [2024-01-10 07:13:46]:TC62A*K451017312Z947
                const regex = /\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\]:(.{20})/g;
                let match = regex.exec(line);
                if (match !== null) {
                    const time = match[1];
                    const carType = match[2].substring(0, 7).trim();
                    const carNumber = match[2].substring(7, 14);
                    // log.info(`时间: ${time}, 车型: ${carType}, 车号: ${carNumber}`);
                    await this.handle(time, carType, carNumber)
                }
            }

            // rl.on('close', async () => {
            // 判断最后一个文件，找到最后一行的时间；
            if (i === 0) {
                log.info("最后一个文件：", fileSlice[i].path)
                if (this.currentGroup.length > 0) {
                    // Check if the last group exceeds the 10-minute threshold
                    if (!compareTimes(new Date(), new Date(this.lastTime))) {
                        log.info("超过10分钟没有新数据，结束当前组：", this.currentGroup.length)
                        await this.postGroup(this.currentGroup);
                        this.currentGroup = [];
                    }
                }
            }
            log.info('File reading completed.');
            // });
        }
    }

    async handle(time: string, carType: string, carNumber: string) {
        if (this.lastTime === null) {
            log.info("第一次运行");
            this.currentGroup.push({carType: carType, carNumber: carNumber, time: time});
        } else if (compareTimes(new Date(time), new Date(this.lastTime))) {
            this.currentGroup.push({carType: carType, carNumber: carNumber, time: time});
        } else {
            log.info("结束当前组，开始新组：", this.currentGroup.length);
            await this.postGroup(this.currentGroup);
            this.currentGroup = [{carType: carType, carNumber: carNumber, time: time}];
        }
        this.lastTime = time;
        await this.postNode(time, carNumber, carType, this.currentGroup[0].time)
    }

    private async postGroup(currentGroup: Group[]) {
        // 发送整列数据
        const trainData: TrainCO = {
            type: "log",
            boxCount: null,
            code: currentGroup[0].time,
            deviceName: config.deviceName,
            direction: "Leave",
            endTime: currentGroup[currentGroup.length - 1].time,
            name: null,
            no: null,
            platformId: config.platformId,
            platformName: config.platformName,
            productName: null,
            senderName: null,
            startTime: currentGroup[0].time,
            stationName: null,
            time: currentGroup[0].time,
            totalNode: currentGroup.length
        }
        await sender.send("train", trainData);
    }

    private async postNode(time: string, carNumber: string, carType: string, time2: string) {
        // 发送节数据
        const nodeData: TrainNodeCO = {
            type: "log",
            code: time,
            containerNumber1: null,
            containerNumber2: null,
            containerType1: null,
            containerType2: null,
            lable: null,
            maxNetWeight: null,
            no: carNumber,
            platformId: config.platformId,
            platformName: config.platformName,
            sort: null,
            speed: null,
            standardTareWeight: null,
            time: time,
            trainCode: time2,
            carType: carType,
            weight: null
        }
        await sender.send("trainNode", nodeData);
    }
}

const logFulongCollector = new LogFulongCollector();
export default logFulongCollector;